export default class Terminal {
    constructor(ip) {
        this.url = `ws://${ip}:8800/ws/`
        this.socket = null
        this.timer = null
    }
    open(containerID) {
        this.close()
        this.socket = new WebSocket(this.url + containerID)
        this.socket.binaryType = 'blob'
        this.socket.onopen = () => {
            this.timer = setInterval(() => { this.socket.send(' ') }, 1000 * 30)
        }
        return this
    }
    send(content) {
        let blob = new Blob([content + "\r\n"], { type: '' })
        //console.log(blob)
        this.socket.send(blob)
    }
    close() {
        this.timer == null || clearInterval(this.timer)
        this.socket == null || this.socket.close()
        this.socket = null
    }
    onopen(callback) {
        this.socket.onopen = callback
    }
    onmessage(callback) {
        this.socket.onmessage = async (e) => {
            callback(await this.blobToText(e.data))
        }
    }
    onclose(callback) {
        this.socket.onclose = callback
    }
    onerror(callback) {
        this.socket.onerror = callback
    }
    blobToText(blob) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.onload = function (event) {
                resolve(event.target.result)
            };
            reader.readAsText(blob, 'UTF-8');
        })

    }
}